<script>
  import {
    addCategory,
    getTree,
    getActiveTree,
    paiContentCategoryActive,
    paiContentCategoryFrozen,
    updateCategory
  } from '@/api/contentCenter'
  import api from '@/api/banner'
  import { getUploadForOSS, POST } from '@/api/banner'

  const baseApi = process.env.VUE_APP_API_BASE_URL

  export default {
    name: 'Index',
    data() {
      return {
        loading: false,
        tableData: [],
        treeData: [],
        typeId: 1,
        columns: [{
            title: '名称',
            dataIndex: 'name',
            key: 'id'
          },
          { title: '状态', key: 'state', scopedSlots: { customRender: 'state' } },
          { title: '操作', key: 'action', scopedSlots: { customRender: 'action' } }
        ],
        page: {
          page: 1,
          limit: 10000
        },
        modal: {
          visible: false,
          title: '',
          form: {},
          rules: {
            name: [
              { required: true, message: '分类名称不能为空', trigger: 'blur' }
            ],
            pid: [
              { required: true, message: '请选择上级分类', trigger: 'change' }
            ]
          }
        },

      }
    },
    mounted() {
      this.getTable()
    },
    methods: {
      handleUpload(e) {
        this.loading = true
        // 读取上传文件参数，2024年11月3日11:42:38
        getUploadForOSS({ fileName: e.file.name }).then(res => {
          if (res.data) {
            let data = res.data;
            const formData = new FormData();
            formData.append("name", e.name);
            formData.append("policy", data.policy);
            formData.append("OSSAccessKeyId", data.ossAccessKeyId);
            formData.append("success_action_status", "200");
            formData.append("signature", data.signature);
            formData.append("key", data.fileKey);
            formData.append("file", e.file);
            this.fileTooss(data.host, formData, res.data.saveFileUrl)
          }
        }).catch(() => {
          this.loading = false
        })
      },

      fileTooss(url, formData, resultUrl) {
        POST(url, formData)
          .then((res) => {
            this.loading = false
            if (res.status == '200') {
              this.modal.form.icon = resultUrl
            }
          })
          .catch(() => {
            this.loading = false
          })
      },

      deleteChildren(arr) {
        const list = arr
        for (let i = list.length; i--; i > 0) {
          if (list[i].children) {
            if (list[i].children.length) {
              this.deleteChildren(list[i].children)
            } else {
              delete list[i].children
            }
          }
        }
        return arr
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.modal.form.id) {
              updateCategory(this.modal.form, this.typeId).then(res => {
                this.$message.success(res.msg)
                this.modal.form = {}
                this.modal.visible = false
                this.getTable()
              })
            } else {
              addCategory(this.modal.form, this.typeId).then(res => {
                this.$message.success(res.msg)
                this.modal.form = {}
                this.modal.visible = false
                this.getTable()
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      handleAdd() {
        this.modal.form = {
          pid: '',
          name: '',
          sort_order: 10,
          icon: '',
          state: 1
        }
        this.modal.visible = true
        this.modal.title = '新增'
      },
      getTable() {
        getTree(this.page, this.typeId).then(res => {
          this.tableData = res.data
        })
        getActiveTree(this.page, this.typeId).then(res => {
          const treeData = JSON.parse(JSON.stringify(res.data))
          const treeDataNew = [{ name: '顶部分类', id: 0, children: treeData }]
          this.treeData = this.deleteChildren(treeDataNew)
        })
      },
      handleEdit(record) {
        const data = JSON.parse(JSON.stringify(record))
        this.modal.form = {
          name: data.name,
          pid: data.pid,
          sort_order: data.sortOrder,
          icon: data.icon,
          id: data.id
        }
        this.modal.visible = true
        this.modal.title = '编辑'
      },
      handleStatus(record) {
        this.$confirm(`您确定要${record.data.state === 1 ? '冻结' : '激活'}吗？`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (record.data.state === 1) {
            paiContentCategoryFrozen([record.id]).then(() => {
              this.$message.success('冻结成功')
              this.getTable()
            })
          } else {
            paiContentCategoryActive([record.id]).then(() => {
              this.$message.success('激活成功')
              this.getTable()
            })
          }
        }).catch(() => {})
      }
    }
  }
</script>

<template>
  <page-header-wrapper :title="false">
    <el-card class="box-card">
      <div slot="header" class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :offset="16" :span="8" style="text-align: right;">
              <span class="table-page-search-submitButtons">
                <a-button icon="plus" style="margin-right: 8px" type="primary" @click="handleAdd">新建</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <el-table :data="tableData" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" border
        default-expand-all row-key="id" style="width: 100%">
        <el-table-column label="名称" prop="name" />
        <el-table-column label="排序号" prop="sortOrder" align="center" />
        <el-table-column label="状态" align="center" width="180">
          <template slot-scope="scope">
            <el-tag v-if="parseInt(scope.row.data.state) === 1">激活</el-tag>
            <el-tag v-if="parseInt(scope.row.data.state) === 2" type="danger">冻结</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="180">
          <template slot-scope="scope">
            <el-link :underline="false" type="primary" @click="handleEdit(scope.row)">编辑
            </el-link>
            <el-link v-if="parseInt(scope.row.data.state) === 2" :underline="false" style="margin-left:10px;"
              type="success" @click="handleStatus(scope.row)">激活
            </el-link>
            <el-link v-if="parseInt(scope.row.data.state) === 1" :underline="false" style="margin-left:10px;"
              type="danger" @click="handleStatus(scope.row)">冻结
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog :title="modal.title" :visible.sync="modal.visible" width="500px" v-loading="loading"
      element-loading-background="rgba(0, 0, 0,0)">
      <el-form ref="ruleForm" :model="modal.form" :rules="modal.rules" class="demo-ruleForm" label-width="100px">
        <el-form-item label="上级分类">
          <el-cascader v-model="modal.form.pid" :options="treeData"
            :props="{ value: 'id',label: 'name',children: 'children',emitPath: false,checkStrictly: true }" clearable
            placeholder="请选择上级分类" style="width: 100%;"></el-cascader>
        </el-form-item>
        <el-form-item label="分类名称">
          <el-input v-model="modal.form.name" clearable placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-upload action="#" :http-request="handleUpload" :show-file-list="false" class="avatar-uploader">
            <img v-if="modal.form.icon !== ''" :src="modal.form.icon" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="modal.form.sort_order" :min="1" label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确认</el-button>
          <el-button @click="modal.visible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </page-header-wrapper>
</template>

<style lang="less" scoped>
  .avatar-uploader ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>